<template>
  <el-dialog :visible.sync="dialogTableVisible" :append-to-body="true" :lock-scroll="false" :title="isEdit?'':''" width="900px" @close="handleCloseDetailDialog">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="120px" >
      <el-form-item :label="$t('table.member_type')">
        <el-select v-model="postForm.level" width="600px" disabled @change="getUserAllList()">
          <el-option :value="1" :label="$t('table.member')"></el-option>
          <el-option :value="0" :label="$t('table.non_member')" ></el-option>
        </el-select>
        <el-button @click="sendToAll()" type="primary">{{ $t('table.send_to_all') }}</el-button>
      </el-form-item>
      <!-- <el-form-item :label="$t('couponfiles.member')">
        <el-col ><el-input v-model="postForm.keyword" @change="getUserAllList()" name="keyword" style="width:320px" placeholder="Email" /></el-col>
      </el-form-item> -->
      <el-form-item :label="$t('couponfiles.member')">
        <el-col >
          <el-select
            v-model="postForm.users"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="Enter keyword"
            :remote-method="getUserAllList"
            :loading="loading"
            style="width: 317px">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <!-- <el-transfer
            v-model="postForm.users"
            :props="{
              key: 'id',
              label: 'name'
            }"
            :titles="userTitle"
            :data="userList"
            :filter-method="filterMethod"
            filterable
          /> -->
        </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDetailDialog">{{ $t('table.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm('postForm')">{{ $t('table.submit') }}</el-button>
    </div>

  </el-dialog>
</template>
<script>

import userApi from '@/api/user/user'
import couponApi from '@/api/coupon/coupon'
import ScrollPane from '../../../../../components/ScrollPane/index'
import i18n from '@/lang/index'

const defaultForm = {
  keyword: '',
  level: 1,
  users: [],
  couponid: 0
}

export default {
  name: 'Sendcoupon',
  components: { ScrollPane },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      rules: {
        area: [{ required: true, message: 'Area is required', trigger: 'change' }],
        discount_type: [{ required: true, message: 'Discount Type is required', trigger: 'change' }]
      },
      isEdit: false,
      dialogTableVisible: false,
      // userlevel: [{ 'id': 1, 'name': i18n.t('couponfiles.member') }, { 'id': 0, 'name': i18n.t('couponfiles.member') }],
      userList: [],
      loading: false,
      userTitle: [i18n.t('couponfiles.member_list'), i18n.t('couponfiles.send_member')]
    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    },
    areaOptions: function() {
      return this.$store.state.locale.areas
    }
  },
  created() {
    this.getUserAllList()
  },

  mounted() {
  },

  methods: {
    showRecord(id) {
      couponApi.showRecord(id).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.postForm = Object.assign({}, this.postForm)
          // this.postForm.level = 1
          this.postForm.users = []
          this.postForm.couponid = id
          this.userList = serviceResponse.data.userList
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleCreateRecord() {
      couponApi.createRecord().then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          // this.postForm.level = 1
          this.userList = serviceResponse.data.userList
        }
      }).catch(err => {
        console.log(err)
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        this.postForm.area = 96
        if (valid) {
          couponApi.sendCoupons(this.postForm).then(response => {
            const serviceResponse = response.data
            if (serviceResponse.code === 0) {
              this.$message({
                type: 'success',
                message: serviceResponse.msg
              })
              this.handleCloseDetailDialog()
            } else {
              this.$message({
                type: 'error',
                message: serviceResponse.msg
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(postForm) {
      this.$refs[postForm].resetFields()
    },

    sendToAll(){
      this.$confirm('Confirm Send?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        couponApi.sendCouponAll(this.postForm).then(response => {
            const serviceResponse = response.data
            if (serviceResponse.code === 0) {
              this.$message({
                type: 'success',
                message: serviceResponse.msg
              })
              this.handleCloseDetailDialog()
            } else {
              this.$message({
                type: 'error',
                message: serviceResponse.msg
              })
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },

    handShowDetailDialog(id) {
      if (id > 0) {
        this.isEdit = true
        this.editId = id
        this.coupon_id = id
        this.showRecord(id)
      } else {
        this.isEdit = false
        this.handleCreateRecord()
        this.postForm = Object.assign({}, defaultForm)
      }
      this.dialogTableVisible = true
    },
    handleCloseDetailDialog() {
      this.resetForm('postForm')
      this.editId = 0
      this.$emit('indexRecord')
      this.dialogTableVisible = false
    },
    getUserAllList(query) {
      if (query !== '') {
        this.loading = true
        // this.listLoading = true
        userApi.indexAllRecord({'register_type':this.postForm.level, 'keyword': query}).then(response => {
          this.loading = false
          var data = response.data
          this.userList = JSON.parse(JSON.stringify(data.data))
        })
      } else {
        this.userList = []
      }
    }
  }
}
</script>

<style>
.el-transfer-panel {
    width: 320px;
}
</style>